package com.example.springboot.service;

import cn.hutool.core.util.StrUtil;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.example.springboot.entity.User;
import com.example.springboot.exception.ServiceException;
import com.example.springboot.mapper.UserMapper;
import org.springframework.stereotype.Service;

/**
 * 功能:
 * 作者: sdj
 * 日期: 2024/12/8 22:21
 */
@Service
public class UserService extends ServiceImpl<UserMapper,User> {

    //重写save方法
    @Override
    public boolean save(User entity) {
        if (StrUtil.isBlank(entity.getName())) entity.setName(entity.getUsername());
        if (StrUtil.isBlank(entity.getPassword())) entity.setPassword("123");
        if (StrUtil.isBlank(entity.getRole())) entity.setRole("用户");
        return super.save(entity);
    }

    //封装根据username查询的方法
    public User getUserByUsername(String username){
        QueryWrapper<User> queryWrapper = new QueryWrapper<>();
        queryWrapper.eq("username",username); //相当于where条件 where username=#{username}
        return getOne(queryWrapper); //相当于 select * from user where username=#{username}
    }

/*
    public List<User> selectByPage(String name, String username, Integer pageNum, Integer pageSize) {
        Integer skipNum = (pageNum-1) * pageSize;
        return userMapper.selectByPage(name,username,skipNum,pageSize);
    }

 */

    public User login(User user) {
        User dbUser = getUserByUsername(user.getUsername());
        if (dbUser == null) throw new ServiceException("用户名或密码错误");
        if (!user.getPassword().equals(dbUser.getPassword())) throw new ServiceException("用户名或密码错误");
        return dbUser;
    }

    public User register(User user) {
        User dbUser = getUserByUsername(user.getUsername());
        if (dbUser != null) throw new ServiceException("用户名已存在!");
        user.setName(user.getUsername());
        save(user);
        return user;
    }

    public void resetPassword(User user) {
        User dbUser = getUserByUsername(user.getUsername());
        if (dbUser == null) throw new ServiceException("用户名不存在");
        if (!dbUser.getPhone().equals(user.getPhone())) throw new ServiceException("手机号码不正确");
        dbUser.setPassword("123");
        updateById(dbUser);   //更新方法

    }
}


